<template>
  <div class="article-list">

    <van-pull-refresh v-model="isreFreshLoading" :success-text="refreshSuccessText" :success-duration="1500"  @refresh="onRefresh" >
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        @load="onLoad"
      >
        <article-item
          v-for="(article, index) in list"
          :key="index"
          :article="article"
        />
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticles } from '@/api/article'
import ArticleItem from '@/components/article-item'

export default {
  name: 'ArticleList',
  components: {
    ArticleItem
  },
  props: {
    channel: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      list: [],
      loading: false, // 加载状态
      finished: false, // 结束状态
      timestamp: null,
      error: false,
      isreFreshLoading: false,
      refreshSuccessText: '成功刷新'
    }
  },
  methods: {
    async onLoad () {
      try {
        const { data } = await getArticles({
          channel_id: this.channel.id, // 频道的id
          timestamp: this.timestamp || Date.now(), // 当前时间戳
          with_top: 1 // 包含置顶
        })
        // 添加数据进list当中
        const { results } = data.data
        this.list.push(...results)
        // 设置结束loading
        this.loading = false
        // 时间戳
        if (results.length) {
          this.timestamp = data.data.pre_timestamp
        } else {
          this.finished = true
        }
        // 处理错误
      } catch (err) {
        this.error = true

        this.loading = false
      }
    },
    // 下拉刷新之后的处理
    async onRefresh () {
      try {
        const { data } = await getArticles({
          channel_id: this.channel.id, // 频道id
          timestamp: Date.now(), // 时间戳
          with_top: 1
        })
        const { results } = data.data
        this.list.unshift(...results)
        this.isreFreshLoading = false
        this.refreshSuccessText = `成功刷新，更新了${results.length}条数据`
      } catch (err) {
        this.refreshSuccessText = '失败的刷新'
        this.isreFreshLoading = false
      }
    }
  }
}
</script>

<style scoped lang="less">
.article-list {
  height: 79vh;
  overflow-y: auto;
}
</style>
